/**
 * 仓库主文件，用于创建仓库
 */

import { createStore, combineReducers } from "redux";
import { composeWithDevTools } from "@redux-devtools/extension";

// 引入拆分出去的 reducers
import counterReducer from "./reducers/counter-reducer";
import todosReducer from "./reducers/todos-reducer";

// 模拟一个 combineReducers
function myCombineReducers(map: any) {
  // 返回一个 reducer 函数, 该函数称为  rootReducer
  return (state: any = {}, action: any) => {
    debugger;
    console.log("rootReducer", state, action);

    // 将 state 与 action 作为参数去调用 每一个子 reducer 函数，然后将他们的返回值赋值上即可。

    // 定义一份最终的 state 数据
    const result: any = {};
    // 遍历 map 对象，将他们的函数都执行一下
    for (let key in map) {
      result[key] = map[key](state[key], action);
    }

    // 最终将 result 作为最终state数据，给返回
    return result;
  };
}

// 合并 reducers
// const rootReducer = combineReducers({
//   count: counterReducer,
// });

// 合并 reducers 使用自己的 myCombineReducers
const rootReducer = myCombineReducers({
  count: counterReducer,
  todos: todosReducer,
});

const store = createStore(rootReducer, composeWithDevTools());

// 导出 store
export default store;
